<?php

namespace app\admin\controller\depot;

use app\common\controller\Backend;

class Storage extends Backend
{
    // 设置关联查询
    protected $relationSearch = true;

    // 当前模型
    protected $model = null;

    // 无需登陆
    protected $noNeedLogin = [];
    // 无需鉴权
    protected $noNeedRight = [];

    public function __construct(){
        parent::__construct();

        $this->model = model('Depot.Storage');
        $this->SupplierModel = model('Depot.Supplier');
        $this->ProductModel = model('Product.Product');
        $this->DepotProductModel = model('Depot.Productstorage');
        $this->BackModel = model('Depot.Back');
        $this->BackProductModel = model('Depot.Productback');

        $statusList = [
            0 => '待审批',
            1 => '审批失败',
            2 => '待入库',
            3 => '入库完成'
        ];

        $typeList = [
            1 => '直销入库',
            2 => '退货入库'
        ];

        $this->assign([
            'statusList' => $statusList,
            'typeList' => $typeList
        ]);
    }

    public function index(){
        $this->request->filter(['strip_tags','trim']);

        if($this->request->isAjax()){
            list($where,$sort,$order,$offset,$limit) = $this->buildparams();

            $total = $this->model 
                ->with(['supplier'])
                ->where($where)
                ->order($sort,$order)
                ->count();

            $list = $this->model
                ->with(['supplier'])
                ->where($where)
                ->order($sort,$order)
                ->limit($offset,$limit)
                ->select();

            // var_dump(collection($list)->toArray());
            // exit;

            $result = [
                'total' => $total,
                'rows' => $list
            ];

            return json($result);
        }

        return $this->view->fetch();
    }

    // 供应商列表选择
    public function supplier(){
        $this->model = model('Depot.Supplier');

        $this->request->filter(['strip_tags','trim']);

        if($this->request->isAjax()){
            list($where,$sort,$order,$offset,$limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->order($sort,$order)
                ->count();
            
            $list = $this->model
                ->where($where)
                ->order($sort,$order)
                ->limit($offset,$limit)
                ->select();

            
            
            $result = [
                'total' => $total,
                'rows' => $list
            ];

            // var_dump(collection($list)->toArray());
            // exit;
            return json($result);
        }

        return $this->view->fetch();
    }


    // 商品列表
    public function product(){
        $this->model = model('Product.Product');
        $this->request->filter(['strip_tags','trim']);
        
        if($this->request->isAjax()){
            list($where,$sort,$order,$offset,$limit) = $this->buildparams();

            $total = $this->model
                ->with(['type','unit'])
                ->where($where)
                ->order($sort,$order)
                ->count();
            
            $list = $this->model
                ->with(['type','unit'])
                ->where($where)
                ->order($sort,$order)
                ->limit($offset,$limit)
                ->select();
            
            $result = [
                'total' => $total,
                'rows' => $list
            ];
            // var_dump(collection($list)->toArray());
            // exit;
            return json($result);

        }
        return $this->view->fetch();
    }

    // 入库
    public function add(){
        if($this->request->isPost()){
            $params = $this->request->param('row/a');
            // var_dump($params);
            // exit;
            // 接收添加的商品数据,json转换为数组结构
            $productlist = json_decode($params['product'],true);

            // 开启事务
            $this->model->startTrans();
            $this->DepotProductModel->startTrans();

            // 封装入库数据
            $StorageData = [
                'code' => build_code('SH'),
                'supplierid' => $params['supplierid'],
                'type' => $params['type'],
                'amount' => $params['total'],
                'remark' => $params['remark'],
                'status' => 0
            ];

            $StorageStutus = $this->model->validate('common/Depot/Storage')->save($StorageData);

            if($StorageStutus === FALSE){
                $this->error($this->model->getError());
                exit;
            }

            // 处理入库的商品

            // 存放封装好的商品数据
            $ProductData = [];

            foreach($productlist as $item){
                $ProductData[] = [
                    'storageid' => $this->model->id,
                    'proid' => $item['id'],
                    'nums' => $item['nums'],
                    'price' => $item['price'],
                    'total' => $item['total']
                ];
            }

            $ProductStatus = $this->DepotProductModel->validate('common/Depot/Productstorage')->saveAll($ProductData);

            if($ProductStatus === FALSE){
                $this->model->rollback();
                $this->error($this->DepotProductModel->getError());
                exit;
            }


            if($StorageStutus === FALSE || $ProductStatus === FALSE){
                $this->DepotProductModel->rollback();
                $this->model->rollback();
                $this->error('新增入库失败');
                exit;
            }else{
                $this->DepotProductModel->commit();
                $this->model->commit();
                $this->success('新增入库成功');
                exit;
            }
            
        }

        return $this->view->fetch();

    }

    // 编辑
    public function edit($ids=NULL){
        $ids = $this->request->param('ids',0,'trim');
        // var_dump($ids);
        // exit;

        // 查询入库是否存在
        $row = $this->model->find($ids);
        // var_dump(collection($row)->toArray());
        // exit;
        if(!$row){
            $this->error('入库信息不存在');
            exit;
        }

        // 查询入库商品是否存在
        $ProductList = $this->DepotProductModel->where('storageid',$row['id'])->select();
        // var_dump(collection($ProductList)->toArray());
        // exit;
        if(!$ProductList){
            $this->error('入库商品信息不存在');
            exit;
        }

        // 查询供应商是否存在
        $supplier = $this->SupplierModel->with(['provinces','citys','districts'])->where('id',$row['supplierid'])->find();
        // var_dump($supplier);
        // exit;

        if($supplier){
            if(!$supplier){
                $this->error('该供应商不存在');
                exit;
            }
        }else{
            // 查询退货单的订单信息
            $back = $this->BackModel->with(['business'])->where(['storageid'=>$row['id']])->find();

            if(!$back){
                $this->error('退货单信息不存在');
                exit;
            }
        }
        
        if($this->request->isPost()){
            $params = $this->request->param('row/a');
            // var_dump($params);
            // 接收添加商品的数据
            $productlist = json_decode($params['product'],true);
            // var_dump($productlist);
            // exit;
            // 开启事务
            $this->model->startTrans();
            $this->DepotProductModel->startTrans();

            // 封装入库数据
            $StorageData = [
                'id' => $row['id'],
                'type' => $params['type'],
                'amount' => $params['total'],
                'remark' => $params['remark'],
                'status' => $row['status']
            ];

            if($row['type'] == 1){
                $StorageData['supplierid'] = $params['supplierid'];
            }

            // 如果等于true说明直销入库
            if($supplier){
                $StorageStutus = $this->model->validate('common/Depot/Storage.edit')->isUpdate(true)->save($StorageData);
            }else{
                $StorageStutus = $this->model->validate('common/Depot/Storage.back_edit')->isUpdate(true)->save($StorageData);
            }

            if($StorageStutus === FALSE){
                $this->error($this->StorageModel->getError());
                exit;
            }

            // 存放商品数据
            $ProductData = [];

            // 封装一个修改时新增的商品数据
            $NewProductData = [];
            // var_dump($productlist);
            // exit;
            foreach($productlist as $item)
            {
                if(isset($item['id']))
                {
                    $ProductData[] = [
                        'id' => $item['id'],
                        'proid' => $item['proid'],
                        'nums' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                    ];
                }else{
                    $NewProductData[] = [
                        'storageid' => $row['id'],
                        'proid' => $item['proid'],
                        'nums' => $item['nums'],
                        'price' => $item['price'],
                        'total' => $item['total'],
                    ];
                }
            }
            // var_dump($ProductData);
            // var_dump($NewProductData);
            // exit;
            $delproid = json_decode($params['delproid']);
            
            if(!empty($delproid)){
                $DelStatus = $this->DepotProductModel->destroy($delproid);

                if($DelStatus === FALSE){
                    $this->model->rollback();
                    $this->error($this->DepotProductModel->getError());
                    exit;
                }
            }

            $NewProductStatus = $this->DepotProductModel->validate('common/Depot/Productstorage')->saveAll($NewProductData);

            $ProductStatus = $this->DepotProductModel->validate('common/Depot/Productstorage.edit')->isUpdate(true)->saveAll($ProductData);

            if($NewProductStatus === FALSE || $ProductStatus === FALSE){
                $this->model->rollback();
                $this->error($this->DepotProductModel->getError());
                exit;
            }

            if($StorageStutus === FALSE || $ProductStatus === FALSE || $NewProductStatus === FALSE){
                $this->model->rollback();
                $this->error('编辑入库单失败');
                exit;
            }else{
                $this->model->commit();
                $this->DepotProductModel->commit();
                $this->success('编辑入库单成功');
                exit;
            }
        }

        // 商品的数据
        $productData = [];

        $ProductModel = model('Product.Product');
        foreach($ProductList as $item){
            $product = $ProductModel->with(['type','unit'])->find($item['proid']);
            
            $productData[] = [
                'id' => $item['id'],
                'price' => $item['price'],
                'nums' => $item['nums'],
                'total' => $item['total'],
                'product' => $product
            ];
        }

        $data = [
            'supplier' => $supplier,
            'row' => $row,
        ];

        // 如果没有供应商
        if(!$supplier){
            $data['back'] = $back;
        }


        // 返回js使用的数据
        $this->assignconfig('Product',['productData'=>$productData]);
        return $this->view->fetch('',$data);
    }

    // 详情
    public function info($ids=NULL){
        $ids = $this->request->param('ids',0,'trim');

        // 查询入库信息
        $row = $this->model->with(['reviewer','admin'])->find($ids);

        if(!$row){
            $this->error('入库信息不存在');
            exit;
        }

        $supplier = $this->SupplierModel->with(['provinces','citys','districts'])->where('id',$row['supplierid'])->find();

        $ProductList = $this->DepotProductModel->where('storageid',$row['id'])->select();

        $productData = [];

        foreach($ProductList as $item)
        {
            $product = model('Product.Product')->with(['type','unit'])->find($item['proid']);

            $productData[] = [
                'id' => $item['id'],
                'price' => $item['price'],
                'nums' => $item['nums'],
                'total' => $item['total'],
                'product' => $product
            ];;

        }

        $data = [
            'row' => $row,
            'supplier' => $supplier,
            'productData' => $productData
        ];


        return $this->view->fetch('',$data);

    }

    // 通过审核
    public function process(){
        if($this->request->isAjax()){
            // var_dump($this->request->param());
            // exit;
            $ids = $this->request->param('ids',0,'trim');
            $status = $this->request->param('status',-1,'trim');

            if($status == 1){
                $data = [
                    'id' => $ids,
                    'status' => 2,
                    'reviewerid' => $this->auth->id
                ];
            }elseif($status == 0){
                $data = [
                    'id' => $ids,
                    'status' => 1,
                    'reviewerid' => $this->auth->id
                ];
            }else{
                $this->error('审核状态有误');
                exit;
            }

            $result = $this->model->isUpdate(true)->save($data);

            if($result === FALSE){
                $this->error('审核失败');
                exit;
            }else{
                $this->success('入库状态更新成功');
                exit;
            }
        }
    }

    // 撤销状态
    public function cancel($ids=NULL){
        if($this->request->isAjax()){
            $ids = $this->request->param('ids',0,'trim');

            $row = $this->model->find($ids);

            if(!$row){
                $this->error('该入库信息不存在');
                exit;
            }

            $data = [
                'id' => $row['id'],
                'status' => 0,
                'reviewerid' => $this->auth->id
            ];

            $result = $this->model->isUpdate(true)->save($data);
            if($result === FALSE){
                $this->error('撤回审核失败');
                exit;
            }else{
                $this->success('撤回审核成功');
                exit;
            }
        }
    }

    // 确认入库
    public function storage(){
        if($this->request->isAjax()){
            $ids = $this->request->param('ids',0,'trim');

            $row = $this->model->find($ids);
            if(!$row){
                $this->error('该入库信息不存在');
                exit;
            }

            $ProductList = $this->DepotProductModel->where('storageid',$ids)->select();
            if(!$ProductList){
                $this->error('该入库商品不存在');
                exit;
            }

            // 开启事务
            $this->model->startTrans();
            $this->ProductModel->startTrans();

            $StorageData = [
                'id' => $row['id'],
                'status' => 3,
                'reviewerid' => $this->auth->id
            ];

            $StorageStutus = $this->model->isUpdate(true)->save($StorageData);
            if($StorageStutus === FALSE){
                $this->error($this->model->getError());
                exit;
            }

            $ProductData = [];
            // 遍历商品
            foreach($ProductList as $item){
                $product = $this->ProductModel->find($item['proid']);

                if($product['id'] == $item['proid']){
                    $ProductData[] = [
                        'id' => $product['id'],
                        'stock' => bcadd($product['stock'],$item['nums'])
                    ];
                }
            }

            $ProductStatus = $this->ProductModel->isUpdate(true)->saveAll($ProductData);

            if($ProductStatus === FALSE){
                $this->model->rollback();
                $this->error($this->ProductModel->getError());
                exit;
            }

            if($StorageStutus === FALSE || $ProductStatus === FALSE){
                $this->model->rollback();
                $this->ProductModel->rollback();
                $this->error('入库失败');
                exit;
            }else{
                $this->model->commit();
                $this->ProductModel->commit();
                $this->success('入库成功');
                exit;
            }
        }
    }

    // 删除(软删除)
    public function del($ids=NULL){
        $ids = $this->request->param('ids',0,'trim');
        $list = $this->model->where(['id'=>['IN',$ids]])->select();
        if(!$list){
            $this->error('该入库信息不存在');
            exit;
        }

        $result = $this->model->destroy($ids);
        
        if($result === FALSE){
            $this->error('删除失败');
            exit;
        }else{
            $this->success('删除成功');
            exit;
        }
    }

    // 回收站
    public function recyclebin(){
        $this->request->filter(['strip_tags','trim']);

        // 判断是否有ajax请求
        if($this->request->isAjax()){
            //获取表格所提交过来筛选和排序的一些参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 表格需要两个返回值参数 总条数和分页的数据
            $total = $this->model
                ->onlyTrashed()
                ->with(['supplier'])
                ->where($where)
                ->order($sort,$order)
                ->count(); //返回查询的总数

            // var_dump($total);
            // exit;
            $list = $this->model
                ->onlyTrashed()
                ->with(['supplier'])
                ->where($where)
                ->order($sort,$order)
                ->limit($offset,$limit)
                ->select();
            // var_dump(collection($list)->toArray());
            // exit;

            // 打印sql语句
            // echo $this->model->getLastSql();
            // exit;

            // 组装数据
            $result = [
                'total' => $total,
                'rows' => $list
            ];
            // 返回给ajax的数据
            return json($result);  

        }
        return $this->view->fetch();
    }

    // 销毁
    public function destroy($ids=NULL){
        $ids = $this->request->param('ids',0,'trim');
        $rows = $this->model->onlyTrashed()->select($ids);
        // var_dump(collection($rows)->toArray());
        // exit;

        if(!$rows){
            $this->error(__('No Results were found'));
            exit;
        }

        // 开启事务
        $this->model->startTrans();
        $this->DepotProductModel->startTrans();

        // 删除
        $DepotProductID = $this->DepotProductModel->where(['storageid'=>['IN',$ids]])->column('id');
        // var_dump($DepotProductID);
        // exit;

        $StorageStutus = $this->model->onlyTrashed()->where(['id'=>['IN',$ids]])->delete(true);

        if($StorageStutus === FALSE){
            $this->error($this->model->getError());
            exit;
        }

        $DepotProductStatus = $this->DepotProductModel->where(['id'=>['IN',$DepotProductID]])->delete(true);

        if($DepotProductStatus === FALSE){
            $this->model->rollback();
            $this->error($this->DepotProductModel->getError());
            exit;
        }

        if($StorageStutus === FALSE || $DepotProductStatus === FALSE){
            $this->DepotProductModel->rollback();
            $this->model->rollback();
            $this->error('销毁失败');
            exit;
        }else{
            $this->DepotProductModel->commit();
            $this->model->commit();
            $this->success('销毁成功');
            exit;
        }

    }
    

    // 恢复
    public function restore($ids=NULL){
        $ids = $this->request->param('ids',0,'trim');
        $row = $this->model->onlyTrashed()->select($ids);

        if(!$row){
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->onlyTrashed()->where(['id'=>$ids])->update(['deletetime'=>null]);

        if($result === FALSE){
            $this->error('恢复数据失败');
            exit;
        }else{
            $this->success('恢复数据成功');
            exit;
        }
    }

}
